import $ from 'jquery';
import BpmnModeler from 'bpmn-js/lib/Modeler';
import customTranslate from './customTranslate/customTranslate';
import propertiesPanelModule from 'bpmn-js-properties-panel';
import propertiesProviderModule from 'bpmn-js-properties-panel/lib/provider/camunda';
import camundaModdleDescriptor from 'camunda-bpmn-moddle/resources/camunda';

import {
  debounce
} from 'min-dash';

import diagramXML from '../resources/newDiagram.bpmn';
//options定义：container,

function BPMN(options){
	this.options=options;
};
BPMN.prototype.create=function(xml){
	//创建的方法
	var that=this;
	var options=that.options;
	var canvas = $(options.canvas);
	var customTranslateModule = {
	  translate: [ 'value', customTranslate ]
	};
	var bpmnModeler = new BpmnModeler({
	  canvas: canvas,
	  propertiesPanel: {
		parent:options.propertiesPanel
	  },
	  additionalModules: [
		propertiesPanelModule,
		propertiesProviderModule,
		customTranslateModule
	  ],
	  moddleExtensions: {
		camunda: camundaModdleDescriptor
	  }
	});

	that.obj=bpmnModeler;
	registerFileDrop($(options.container),that.importXml);
	if(xml==null||xml=='undefined'){
		that.importXml(diagramXML);
	}else{	
		that.importXml(xml);
	}
	
	that.obj.attachTo(canvas);

};
function registerFileDrop(container, callback) {

  function handleFileSelect(e) {
    e.stopPropagation();
    e.preventDefault();

    var files = e.dataTransfer.files;

    var file = files[0];

    var reader = new FileReader();

    reader.onload = function(e) {

      var xml = e.target.result;

      callback(xml);
    };

    reader.readAsText(file);
  }

  function handleDragOver(e) {
    e.stopPropagation();
    e.preventDefault();

    e.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
  }

  container.get(0).addEventListener('dragover', handleDragOver, false);
  container.get(0).addEventListener('drop', handleFileSelect, false);
}



BPMN.prototype.importXml=function(xml){
	var that=this;
	that.obj.importXML(xml, function(err) {
		if (err) {
		  console.error('error');
		} else {
		 console.log('success');
		}
	  });
}
BPMN.prototype.destory=function(){
	//销毁的方法
	var that=this;
	that.obj.detach();
};
BPMN.prototype.saveXml=function(call){
	//销毁的方法
	var that=this;
	that.obj.saveXML({ format: true }, function(err, xml) {
		call(err, xml);
	});
};
window.$BPMN=function(options){
	var mBomn=new BPMN(options);
	return mBomn;
};

